﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using MySqlConnector;
using System.Data.SqlClient;

namespace SP.EFcore
{
    public class DapperFactory
    {
        /// <summary>
        /// Dapper实例（采用单列模式）
        /// </summary>
        private IConfiguration configuration { get; set; }
        //返回连接实例
       // private static IDbConnection dbConnection = null;
        //静态变量保存类的实例
        private static DapperFactory uniqueInstance;
       // private static DapperFactory uniqueInstance = new DapperFactory(); 饿汉模式 ：不管用没用到 先实例化对象
        //定义一个标识确保线程同步
        private static readonly object locker = new object();
        /// <summary>
        /// 私有构造方法，使外界不能创建该类的实例，以便实现单例模式
        /// </summary>
        private DapperFactory()
        {
            configuration = new ConfigurationBuilder()
                .Add(new JsonConfigurationSource
                {
                    Path = "appsettings.json",
                    ReloadOnChange = true,
                }).Build();
        }
        /// <summary>
        /// 获取实例，这里为单例模式，保证只存在一个实例
        /// </summary>
        /// <returns></returns>
        public static DapperFactory GetInstance()
        {
            //双重锁定实现单例模式，在外层价格判空条件主要是为了减少加锁、释放锁的不必要的损耗
            if (uniqueInstance == null)
            {
                lock (locker) //懒汉模式下一定要加锁 否则多线程高并发的时候，就会创建出来两个实例
                {
                    if (uniqueInstance == null)
                    {
                        uniqueInstance = new DapperFactory();//懒汉模式
                    }
                }
            }
            return uniqueInstance;
        }
        /// <summary>
        /// 创建数据库连接对象（采用的设计模式 工厂模式）
        /// </summary>
        /// <returns></returns>
        public IDbConnection GetDbConnection()
        {
              //连接实例
            IDbConnection dbConnection = null;
                //读取配置文件中的数据库服务器类型mysql或SQLserver
                string dbType = configuration["DbServerType"];
                //读取配置文件中的连接字符串
                string _connectionString = configuration.GetConnectionString("conn");
                switch (dbType)
                {
                    case "MySql":
                        dbConnection = new MySqlConnection(_connectionString);
                        break;
                    case "SqlServer":
                        dbConnection = new SqlConnection(_connectionString);
                        break;
                }
            
            return dbConnection;
        }
    }
}
